<template>
  <div>
    <div class="app-container"   v-if="opendetail == true" >
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

<!--        <el-form-item label="商户编号" prop="merchantCode">-->
<!--          <el-input-->
<!--            v-model="queryParams.merchantCode"-->
<!--            placeholder="请输入商户编号"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item label="负责人姓名" prop="contactName" label-width="100px">
          <el-input
            v-model="queryParams.contactName"
            placeholder="请输入商户姓名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNumber">
          <el-input
            v-model="queryParams.idCardNumber"
            placeholder="请输入身份证号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="营业执照编号" prop="businessLicenseNumber" label-width="100px">
          <el-input
            v-model="queryParams.businessLicenseNumber"
            placeholder="请输入营业执照编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="店名" prop="shopName">
          <el-input
            v-model="queryParams.shopName"
            placeholder="请输入店名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="经营区域" prop="businessArea" label-width="100px">
          <el-input
            v-model="queryParams.businessArea"
            placeholder="请输入经营区域"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress" label-width="100px">
          <el-input
            v-model="queryParams.detailedAddress"
            placeholder="请输入详细地址"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="审核状态" prop="auditStatus" label-width="100px">
          <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable style="width: 150px">
            <el-option
              v-for="dict in sys_audit_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="营业时间" prop="businessHours">
          <el-input
            v-model="queryParams.businessHours"
            placeholder="请输入营业时间"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>


        <el-form-item label="审核时间" style="width: 308px">
          <el-date-picker
            v-model="daterangeReviewTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="提交审核时间" style="width: 308px" label-width="100px">
          <el-date-picker
            v-model="daterangeSubmitTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>

        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['masterrabbit-kaixuan:merchantreviews:export']"
          >导出</el-button>
        </el-col>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="merchantreviewsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="审核记录ID" align="center" prop="reviewId" />-->

<!--        <el-table-column label="商户编号" align="center" prop="merchantCode" />-->
        <el-table-column label="负责人姓名" align="center" prop="contactName" />
<!--        <el-table-column label="身份证号" align="center" prop="idCardNumber" />-->
        <el-table-column label="营业执照编号" align="center" prop="businessLicenseNumber" />
        <el-table-column label="店名" align="center" prop="shopName" />

        <el-table-column label="经营区域" align="center" prop="businessArea" />
        <el-table-column label="详细地址" align="center" prop="detailedAddress" />


        <el-table-column label="审核状态" align="center" prop="auditStatus">
          <template #default="scope">
            <dict-tag :options="sys_audit_state" :value="scope.row.auditStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="营业时间" align="center" prop="businessHours" />
        <el-table-column label="用户名" align="center" prop="sysUser1.userName" />

        <el-table-column label="审核人姓名" align="center" prop="sysUser2.userName" />

        <el-table-column label="审核时间" align="center" prop="reviewTime" width="180"/>
        <el-table-column label="提交审核时间" align="center" prop="submitTime" width="180"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="getdetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改商户信息审核对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="merchantreviewsRef" :model="form" :rules="rules" label-width="80px">

          <el-form-item label="商户编号" prop="merchantCode">
            <el-input v-model="form.merchantCode" placeholder="请输入商户编号" />
          </el-form-item>
          <el-form-item label="负责人姓名" prop="contactName">
            <el-input v-model="form.contactName" placeholder="请输入负责人姓名" />
          </el-form-item>

          <el-form-item label="营业执照编号" prop="businessLicenseNumber">
            <el-input v-model="form.businessLicenseNumber" placeholder="请输入营业执照编号" />
          </el-form-item>
          <el-form-item label="店名" prop="shopName">
            <el-input v-model="form.shopName" placeholder="请输入店名" />
          </el-form-item>

          <el-form-item label="经营区域" prop="businessArea">
            <el-input v-model="form.businessArea" placeholder="请输入经营区域" />
          </el-form-item>
          <el-form-item label="详细地址" prop="detailedAddress">
            <el-input v-model="form.detailedAddress" placeholder="请输入详细地址" />
          </el-form-item>


          <el-form-item label="审核状态" prop="auditStatus">
            <el-radio-group v-model="form.auditStatus">
              <el-radio
                v-for="dict in sys_audit_state"
                :key="dict.value"
                :label="parseInt(dict.value)"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="营业时间" prop="businessHours">
            <el-input v-model="form.businessHours" placeholder="请输入营业时间" />
          </el-form-item>

          <el-form-item label="审核人ID" prop="reviewerId">
            <el-input v-model="form.reviewerId" placeholder="请输入审核人ID" />
          </el-form-item>
          <el-form-item label="审核时间" prop="reviewTime">
            <el-date-picker clearable
              v-model="form.reviewTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择审核时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="提交审核时间" prop="submitTime">
            <el-date-picker clearable
              v-model="form.submitTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择提交审核时间">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <div v-if="opendetail == false">
      <div>
        <el-button type="primary" @click="backshop">返回</el-button>
      </div>
      <div>
        <h2>商户信息</h2>

        <!-- 表格展示主要信息 -->
        <el-table :data="[shopData]" border style="width: 100%">
          <el-table-column prop="auditStatus" label="审核状态" >
            <template #default="scope">
              <dict-tag :options="sys_audit_state" :value="scope.row.auditStatus"/>
            </template>
          </el-table-column>
          <el-table-column prop="businessArea" label="营业面积" />
          <el-table-column prop="businessHours" label="营业时间" />
          <el-table-column prop="businessLicenseNumber" label="营业执照号" />
<!--          <el-table-column prop="contactName" label="联系人" />-->
          <el-table-column prop="phoneNumber" label="联系电话" />
<!--          <el-table-column prop="merchantCode" label="商户代码" />-->
          <el-table-column prop="shopBalance" label="店铺余额" />
          <el-table-column prop="shopName" label="店铺名称" />
          <el-table-column prop="sysUser1.userName" label="商户姓名" />
        </el-table>
        <div style="margin-left: 20px">
        <!-- 详细信息左右分布 -->
          <h3>详细信息</h3>
          <el-row :gutter="20" >
            <el-col :span="12">
              <p><strong>商户：</strong> {{ shopData.sysUser1.userName || "无" }}</p>
            </el-col>
            <el-col :span="12">
              <p><strong>创建时间：</strong> {{ shopData.submitTime || "无" }}</p>
            </el-col>
            <el-col :span="12">
              <p><strong>当前操作人：</strong> {{ user.name || "无" }}</p>
            </el-col>
            <el-col :span="12">
              <p><strong>审核时间：</strong> {{ currentDate  }}</p>
            </el-col>
            <el-col :span="12">
              <p><strong>备注：</strong> {{ shopData.remark || "无" }}</p>
            </el-col>
          </el-row>


          <!-- 地址信息 -->
          <h3>地址信息</h3>
          <el-card>
            <p><strong>详细地址：</strong> {{ shopData.detailedAddress }}</p>
          </el-card>

          <!-- 图片信息 -->
          <h3>图片信息</h3>
          <el-row :gutter="20">
            <el-form>
              <p>营业执照</p>
              <el-col :span="8">
                <img
                    v-for="(url, index) in businessLicenseImage"
                    :key=" index"
                    :src="url"
                    style="width: 100px; height: 100px"
                    fit="cover"/>
              </el-col>
            </el-form>
            <el-form>
              <p>身份证</p>
              <el-col :span="8" v-if="shopData.idCardImageId">
                <img
                    v-for="(url, index) in idCardImage"
                    :key=" index"
                    :src="url"
                    style="width: 100px; height: 100px"
                    fit="cover"/>
              </el-col>
            </el-form>
            <el-form>
              <p>店铺门面</p>
              <el-col :span="8" v-if="shopData.storefrontImageId ">
                <img
                    v-for="(url, index) in storefrontImage"
                    :key=" index"
                    :src="url"
                    style="width: 100px; height: 100px"
                    fit="cover"
                />
              </el-col>
            </el-form>
<!--            <img src="https://siwjd.oss-cn-beijing.aliyuncs.com/image/1742287286313_QQ20250318-163359.png"/>-->
          </el-row>
        </div>
      </div>
      <el-form style="margin-left: 50px">
        <el-button  type="primary" icon="Edit" @click="crosshandleUpdate(scope.row)" v-hasPermi="['masterrabbit-kaixuan:merchantreviews:edit']">审核通过</el-button>
        <el-button style="background-color: #ed5565" type="primary" icon="Edit" @click="uncrosshandleUpdate(scope.row)" v-hasPermi="['masterrabbit-kaixuan:merchantreviews:edit']">审核不通过</el-button>
      </el-form>
    </div>

  </div>
</template>

<script setup name="Merchantreviews">
import { listMerchantreviews, getMerchantreviews, delMerchantreviews, addMerchantreviews, updateMerchantreviews } from "@/api/masterrabbit-kaixuan/merchantreviews";
import {getimages} from "@/api/masterrabbit-kaixuan/orders"

import useUserStore from "../../store/modules/user.js";
import {getUserName} from "../../api/masterrabbit-kaixuan/merchantreviews.js";
import {updateMerchants} from "../../api/masterrabbit-kaixuan/merchants.js";

const { proxy } = getCurrentInstance();
const { sys_audit_state } = proxy.useDict('sys_audit_state');

const merchantreviewsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeReviewTime = ref([]);
const daterangeSubmitTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    reviewId: null,
    merchantId: null,
    merchantCode: null,
    contactName: null,
    idCardNumber: null,
    businessLicenseNumber: null,
    shopName: null,
    phoneNumber: null,
    businessArea: null,
    detailedAddress: null,
    idCardImageId: null,
    businessLicenseImageId: null,
    storefrontImageId: null,
    longitude: null,
    latitude: null,
    auditStatus: null,
    businessHours: null,
    userId: null,
    shopBalance: null,
    reviewerId: null,
    reviewTime: null,
    submitTime: null,
    sysUser1: null,
    sysUser2: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商户信息审核列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeReviewTime && '' != daterangeReviewTime) {
    queryParams.value.params["beginReviewTime"] = daterangeReviewTime.value[0];
    queryParams.value.params["endReviewTime"] = daterangeReviewTime.value[1];
  }
  if (null != daterangeSubmitTime && '' != daterangeSubmitTime) {
    queryParams.value.params["beginSubmitTime"] = daterangeSubmitTime.value[0];
    queryParams.value.params["endSubmitTime"] = daterangeSubmitTime.value[1];
  }
  listMerchantreviews(queryParams.value).then(response => {
    merchantreviewsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    reviewId: null,
    merchantId: null,
    merchantCode: null,
    contactName: null,
    idCardNumber: null,
    businessLicenseNumber: null,
    shopName: null,
    phoneNumber: null,
    businessArea: null,
    detailedAddress: null,
    idCardImageId: null,
    businessLicenseImageId: null,
    storefrontImageId: null,
    longitude: null,
    latitude: null,
    auditStatus: null,
    businessHours: null,
    userId: null,
    shopBalance: null,
    reviewerId: null,
    reviewTime: null,
    submitTime: null
  };
  proxy.resetForm("merchantreviewsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeReviewTime.value = [];
  daterangeSubmitTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.reviewId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商户信息审核";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _reviewId = row.reviewId || ids.value
  getMerchantreviews(_reviewId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商户信息审核";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["merchantreviewsRef"].validate(valid => {
    if (valid) {
      if (form.value.reviewId != null) {
        updateMerchantreviews(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMerchantreviews(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _reviewIds = row.reviewId || ids.value;
  proxy.$modal.confirm('是否确认删除商户信息审核编号为"' + _reviewIds + '"的数据项？').then(function() {
    return delMerchantreviews(_reviewIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('masterrabbit-kaixuan/merchantreviews/export', {
    ...queryParams.value
  }, `merchantreviews_${new Date().getTime()}.xlsx`)
}


/** 跳转详情页 */
const opendetail = ref(true)
const shopData = ref({})
const businessLicenseImage = ref([])
const idCardImage = ref([])
const storefrontImage = ref([])

const  getdetail = async (row)=>{
  console.log("点击触发")
  opendetail.value = false;
  shopData.value = row;
  businessLicenseImage.value = await getimage(row.businessLicenseImageId)
  idCardImage.value = await getimage(row.idCardImageId)
  storefrontImage.value = await getimage(row.storefrontImageId)
  console.log(businessLicenseImage.value)
  console.log(idCardImage.value)
  console.log(storefrontImage.value)


}



/** 返回商店列表页 */
function backshop() {
  opendetail.value = true;
}

const user = useUserStore();
console.log(user.name)
console.log(user.id)


const currentDateTime = computed(() => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 补零
  const day = String(date.getDate()).padStart(2, "0"); // 补零

  // 获取时分秒
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
});

const currentDate = computed(() => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 补零
  const day = String(date.getDate()).padStart(2, "0"); // 补零

  return `${year}-${month}-${day}`;
});

/** 审核通过按钮 */
function crosshandleUpdate(row){
  reset();
  const _reviewId = row.reviewId || ids.value
  getMerchantreviews(_reviewId).then(response => {
    form.value = response.data;

    title.value = "修改商户信息审核";
  });
  /** 更改审核表 */
  updateMerchantreviews(form.value).then(response => {
    proxy.$modal.msgSuccess("修改成功");
    form.value.auditStatus = 2
    form.value.reviewTime = currentDateTime;

  });
  /** 更改商户信息表表 */
  updateMerchants(form.value).then(response => {
    proxy.$modal.msgSuccess("修改成功");
    getList();
  });
}

/** 审核未通过按钮 */
function uncrosshandleUpdate(row){
  reset();
  const _reviewId = row.reviewId || ids.value
  getMerchantreviews(_reviewId).then(response => {
    form.value = response.data;
    form.value.auditStatus = 3
    form.value.reviewTime = currentDateTime;
    title.value = "修改商户信息审核";
  });
  /** 更改审核表 */
  updateMerchantreviews(form.value).then(response => {
    proxy.$modal.msgSuccess("修改成功");
  });
  /** 更改商户信息表表 */
  updateMerchants(form.value).then(response => {
    proxy.$modal.msgSuccess("修改成功");

    getList();
  });
}
const getimage = async (id)=>{
   let res = await getimages(id);
  console.log(res)
  return res;
}


getList();
</script>
